const Ws = require('ws');
const express = require('express')
const router = express.Router()
const Public = require('../../model/publicmsg');
const Private = require('../../model/privatemsg')
router.use('/', (req, res, next) => {
    ((Ws) => {
        const server = new Ws.Server({ port: 4000 });

        const init = () => {
            bindEvent();
        }

        function bindEvent() {
            server.on('open', handleOpen);
            server.on('close', handleClose);
            server.on('error', handleError);
            server.on('connection', handleConnection)
        }

        function handleOpen() {
            // console.log(WebSocket)
            console.log('open 开启')
        }

        function handleClose() {
            console.log('BE:WebSocket 关闭')
        }

        function handleError() {
            console.log('BE:WebSocket 异常')
        }

        function handleConnection(ws) {
            console.log('连接成功')
            ws.on('message', data => {
                data = JSON.parse(data)
                if (!data.msgType) {
                    ws.uid = data.id
                    console.log('给ws赋值id走到这里来', data)
                } else {
                    return
                }
            })
            ws.on('message', handleMessage)
        }

        function handleMessage(msg) {
            let data = JSON.parse(msg)
            console.log('普通信息走这里来', data)
            if (data.msgType == 0) {
                return
            } else if (data.msgType == 1) { //群聊消息
                console.log('收到一条群聊消息')
                let public = new Public({
                    user: data.send_id,
                    message: data.msg,
                    date: data.dateTime,
                })
                public.save()
                    // console.log(server.clients)
                server.clients.forEach(c => {
                    // console.log(c.uid)
                    c.send(msg)
                })
            } else { //私聊信息
                console.log('收到了一条私聊信息')
                let private = new Private({
                    sendUser: data.send_id,
                    receiveUser: data.receive_id,
                    msg: data.msg,
                    date: data.dateTime
                })
                private.save()
                let receiveId = data.receive_id
                let sendId = data.send_id
                server.clients.forEach(c => {
                    // console.log(c.uid)
                    if (receiveId == c.uid) {
                        console.log(c.uid)
                        c.send(msg)
                    }
                    return
                })
            }
        }
        init();
    })(Ws)
    next()
})

module.exports = router